﻿using System.Text.RegularExpressions;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System;
using System.Drawing;
using System.Text;

namespace AutoPageHelper
{
    public class MyUtility
    {
        private static string[] RegexWildChars = new string[] { "\\", "?", ".", "*", "+", "^", "|", "$", "(", ")", "[", "]", "{", "}" };
        public static Regex GetRegex(string text)
        {
            string pattern = text;
            if (!pattern.StartsWith("^"))
            {
                foreach (string wc in RegexWildChars)
                {
                    pattern = pattern.Replace(wc, "\\" + wc);
                }
            }
            if (!pattern.StartsWith("^"))
                pattern = "^" + pattern;
            if (!pattern.EndsWith("$"))
                pattern = pattern + "$";
            Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
            return regex;
        }

        public static bool IsVariableName(string name)
        {
            Regex regvar = new Regex("^[_a-zA-Z][_a-zA-Z0-9]*$");
            return regvar.IsMatch(name);
        }

        public static bool IsRegexPattern(string pattern)
        {
            return (pattern[0] == '^');
        }
        [DllImport("shell32.dll")] 
        public static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);
        public static void AssociateExt(string ExeFilePath, string FileExt, string FileTypeName, string IconFilePath)
        {
            RegistryKey Subkey = Registry.ClassesRoot.OpenSubKey(FileExt, true);
            if (Subkey == null)
                Subkey = Registry.ClassesRoot.CreateSubKey(FileExt);
            Subkey.SetValue("", FileTypeName);
            RegistryKey defaultIcon = Subkey.CreateSubKey("DefaultIcon");
            defaultIcon.SetValue("", IconFilePath);
            Subkey.SetValue("Content Type", "text/plain");
            Subkey = Subkey.CreateSubKey("shell\\open\\command");
            Subkey.SetValue("", string.Format("\"{0}\" \"%1\"", ExeFilePath));
            SHChangeNotify(0x8000000, 0, IntPtr.Zero, IntPtr.Zero);
        }

        //HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3, 1407设置为0允许访问剪贴板
        public static void SetClipboardAllowed()
        {
            RegistryKey subKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3", true);
            if (subKey == null)
                return;
            object v = subKey.GetValue("1407");
            if(v == null)
                subKey.SetValue("1407", 0);
            int i = Convert.ToInt32(v);
            if (i != 0)
                subKey.SetValue("1407", 0);
        }

    }
}
